// All of the Node.js APIs are available in the preload process.
// It has the same sandbox as a Chrome extension.

const { fillTable } = require('./utils/issue');

const sd = require('./utils/sdate')

// 2020-10-23 23:48 sheyifan Issue: put require to top
var ipcRenderer = require('electron').ipcRenderer;
window.addEventListener('DOMContentLoaded', function () {
    var replaceText = function (selector, text) {
        var element = document.getElementById(selector)
        if (element)
            element.innerText = text
    }
    for (var _i = 0, _a = ['chrome', 'node', 'electron']; _i < _a.length; _i++) {
        var type = _a[_i]
        replaceText(type + "-version", process.versions[type])
	}

	// 2020-10-23 sheyifan Issue: communicate between main and render process
	// 2020-10-23 23:48 sheyifan Issue: remove synchronize IPC(internal process communication)
	// 2020-10-23 23:48 sheyifan Issue: run IPC after dom loaded (put into block)
	ipcRenderer.on('data', function (event, arg) {
		if(window.document.location.href.endsWith('index.html')) {
			// args: message to get
			let iss = require('./utils/issue')
			/** @type {import('./utils/sdate').DayIssue} */
			let data = iss.normalize(arg)
			
			iss.fillBadgeDropdownMenu(data, document)
		}
		else if(window.document.location.href.endsWith('tables.html')) {
			/** 
			 * 2020-10-31 sheyifan Issue: table to hold undone issues
			 * @type {HTMLTableElement} 
			 */
			let tableFinished = document.querySelector('#finish')
			/** 
			 * 2020-10-31 sheyifan Issue: table to hold unfinished issues
			 * @type {HTMLTableElement} 
			 */
			let tableUndone = document.querySelector('#undone')
			/** 
			 * 2020-10-31 sheyifan Issue: table to hold appointted issues
			 * @type {HTMLTableElement} 
			 */
			let tableAppointed = document.querySelector('#appointed')

			let iss = require('./utils/issue')
			// args: message to get
			/** @type {import('./utils/sdate').DayIssue} */
			let data = iss.normalize(arg)
			
			let filterResult = filterByOne(data)
			let undoneData = filterResult.undoneData
			let finishData = filterResult.finishData

			fillTable(undoneData, tableUndone)
			fillTable(finishData, tableFinished)
			// Fill appointed json data into table (as well as adding rows)
			fillTable(data.预约, tableAppointed)

			// 2020-11-22 sheyifan Issue: fill modal on clicking each table row after
			// rows finish rendering
			let sdom = require('./utils/sdom')
			sdom.fillModalOnClickTableRow()

			/** @type {HTMLButtonElement} */
			let createIssueButton = document.querySelectorAll("#myModal .create-issue").item(0)
			sdom.fillModalDate()
		}
	});

	// 2020-10-23 sheyifan Issue: communicate between main and render process
	// 2020-10-23 23:48 sheyifan Issue: remove synchronize IPC(internal process communication)
	// 2020-10-23 23:48 sheyifan Issue: run IPC after dom loaded (put into block)
	ipcRenderer.on('overview-data', function (event, arg) {
		if(window.document.location.href.endsWith('index.html')) {
			// args: message to get
			/** 
			* @type {{
			*     T0: import('./utils/sdate').FinishData
			*     T1: import('./utils/sdate').FinishData
			* }} 
			* */
			let data = arg
			let iss = require('./utils/issue')
			iss.fillDashboard(data, document)
		}
	});
	
	// 2020-10-24 16:52 sheyifan Issue: operate DOM in rendering process with the following. Can
	// use complete version of Node.js API in preload.js (except something about 'main', so cannot
	// execute execute javascript in rendering process
	// 2020-10-27 17:03 sheyifan Issue: simplify if...else
	if(window.document.location.href.endsWith('index.html')) {
		let date = sd.getDate(0)
		// 2020-10-26 11:01 sheyifan Issue: transform from JSON to string (cannot use toString()), which
		// will transform JSON into '[object Object]'
		ipcRenderer.send('need-overview', JSON.stringify(date))
		// 2020-10-26 11:01 sheyifan Issue: transform from JSON to string (cannot use toString()), which
		// will transform JSON into '[object Object]'
		// 2020-10-27 16:52 sheyifan Issue: emit request according to current url
		ipcRenderer.send('need-data', JSON.stringify(date))
	}
	else if(window.document.location.href.endsWith('tables.html')) {
		let date = sd.getDate(0)
		// 2020-10-26 11:01 sheyifan Issue: transform from JSON to string (cannot use toString()), which
		// will transform JSON into '[object Object]'
		// 2020-10-27 16:52 sheyifan Issue: emit request accordinf to current url
		ipcRenderer.send('need-data', JSON.stringify(date))
		registerDatePicker(document, ipcRenderer)
	}
})

/**
 * 2020-11-04 sheyifan Issue: register message trigger onto date picker
 * @param {Document} document 
 * @param {Electron.IpcRenderer} ipcRenderer
 */
function registerDatePicker(document, ipcRenderer) {
	/** @type {HTMLInputElement} */
	let currentDatePicker = document.querySelector("#current-date")
	currentDatePicker.addEventListener('change', (e) => {
		let splitted = currentDatePicker.value.split("-")
		let year = splitted[0]
		let month = splitted[1]
		let day = splitted[2]
		let date = new Date(Number.parseInt(year), Number.parseInt(month) - 1, Number.parseInt(day))
		ipcRenderer.send('get-by-date', JSON.stringify({
			year: year,
			month: month,
			day: day,
			date: date
		}))
	})
}

/**
 * 2020-11-04 sheyifan Issue: seperate data by two group: state == 0 and state != 0 
 * @param {import('./utils/sdate').DayIssue} data 
 * @returns {{
 *     finishData: import('./utils/sdate').DayIssue,
 *     undoneData: import('./utils/sdate').DayIssue
 * }}
 */
function filterByOne(data) {
	// Fill undone json data into table (as well as adding rows)
	let undoneData = {
		"日": data.日,
		"继承": data.继承,
		"T0事项": data.T0事项.filter((e) => e.完成状态 < 1 && e.完成状态 >= 0),
		"T1事项": data.T1事项.filter((e) => e.完成状态 < 1 && e.完成状态 >= 0),
		"T2事项": data.T2事项.filter((e) => e.完成状态 < 1 && e.完成状态 >= 0),
		"预约": (data.预约 != undefined) ? data.预约 : {
			日: data.日,
			继承: false,
			T0事项: [],
			T1事项: [],
			T2事项: []
		}
	}
	// Fill finished json data into table (as well as adding rows)
	let finishData = {
		"日": data.日,
		"继承": data.继承,
		"T0事项": data.T0事项.filter((e) => e.完成状态 === 1),
		"T1事项": data.T1事项.filter((e) => e.完成状态 === 1),
		"T2事项": data.T2事项.filter((e) => e.完成状态 === 1),
		"预约": (data.预约 != undefined) ? data.预约 : {
			日: data.日,
			继承: false,
			T0事项: [],
			T1事项: [],
			T2事项: []
		}
	}

	return {
		finishData: finishData,
		undoneData: undoneData
	}
}